import axios from 'axios'
import Cookies from 'js-cookie'

/** 窗口通讯消息类型 */
export enum MESSAGE_EVENT_TYPE {
  LOGIN_SUCCESS,
  LOGIN_TIMEOUT,
  PAGE_NAVIGATE,
}

export function sendMessage(msg: any, type: MESSAGE_EVENT_TYPE) {
  const origin = window.location.origin
  const targetWindow = window.parent
  const toOrigin = import.meta.env.VITE_POST_MESSAGE_ORIGIN || origin
  targetWindow.postMessage({
    type,
    message: msg,
  }, toOrigin)
  console.log(`[iframe] sent ${type === MESSAGE_EVENT_TYPE.LOGIN_TIMEOUT ? 'timeout' : 'navigation'} to [${toOrigin}].`)
}

const api = axios.create({
  baseURL: SERVICE_BASIC,
  timeout: 3 * 60 * 1000,
})

api.interceptors.request.use((config) => {
  config.headers.token = Cookies.get('token')
  return config
}, (error) => {
  return Promise.reject(error)
})

api.interceptors.response.use((response) => {
  // 2xx
  const { code, message } = response.data
  // 登录超时或未登录
  if (code === 401) {
    Cookies.remove('token')
    sendMessage(message ?? response.data.message, MESSAGE_EVENT_TYPE.LOGIN_TIMEOUT)
  }
  return response.data
}, (error) => {
  // >2xx
  return Promise.reject(error)
})

export default api
